package com.egaleye.core.context;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class EgaleyeApplicationContext implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(EgaleyeApplicationContext.applicationContext == null ){
            EgaleyeApplicationContext.applicationContext = applicationContext;
        }
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name) {
        Object obj = null;
        try {
            obj = getApplicationContext().getBean(name);
            return obj;
        } catch (BeansException e) {
            return obj;
        }
    }

    public static <T> T getBean(Class<T> clazz) {
        T t = null;

        try {
            t = getApplicationContext().getBean(clazz);
            return t;
        } catch (BeansException e) {
            return t;
        }
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        T t = null;

        try {
            t = getApplicationContext().getBean(name, clazz);
            return t;
        } catch (BeansException e) {
            return t;
        }
    }

}
